package com.colin.jipay.activity;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.LogUtils;
import com.colin.jipay.BaseActivity;
import com.colin.jipay.NotificationService;
import com.colin.jipay.R;
import com.colin.jipay.WebService;
import com.colin.jipay.config.ActConst;
import com.colin.jipay.nxys.helper.NxysHelper;
import com.colin.jipay.nxys.helper.NxysShopOrderBean;
import com.colin.jipay.starpos.bean.PushStarPosBean;
import com.colin.jipay.utils.AbSharedUtil;
import com.colin.jipay.utils.GsonUtils;
import com.colin.jipay.utils.JSONUtil;
import com.colin.jipay.utils.LogUtil;
import com.colin.jipay.utils.MD5;
import com.colin.jipay.utils.PayHelperUtils;
import com.colin.jipay.utils.SerializableHashMap;
import com.colin.jipay.utils.StringUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.net.URI;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.colin.jipay.config.ActConst.alipay_sendcode_url;
import static com.colin.jipay.config.ActConst.unionpay_sendcode_url;
import static com.colin.jipay.config.ActConst.unionpay_sendorder_url;

public class MainActivity extends BaseActivity {

    public static String itemId, skuId, id, tid, money;
    private static JSONArray _jsonArray;
    private static int codeIndex;
    public static TextView console;
    private static ScrollView scrollView;
    public static WebService mWebService;
    public TextView setBtn;
    @BindView(R.id.account)
    TextView account_tab;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.toolbar_2)
    Toolbar toolbar;
    @BindView(R.id.imei)
    TextView imei;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        ButterKnife.bind(this);

        sendmsg("账号：" + AbSharedUtil.getString(getApplicationContext(), "account") + " 登录成功!");
        sendmsg("启动WS服务!");
        //webcoket开始处理
        String w = AbSharedUtil.getString(getApplicationContext(), "url");
        w = w.replace("https", "ws");
        w = w.replace("http", "ws");
        w = w + ":9501";
        sendmsg("正在连接WS");
        AbSharedUtil.putString(getApplicationContext(), "wscode", "ok");
        AbSharedUtil.putString(getApplicationContext(), "ws", w);


        console = (TextView) findViewById(R.id.console);
        scrollView = (ScrollView) findViewById(R.id.scrollview);

        setSupportActionBar(toolbar);//设置当前的Actionbar为我们的Toolbar

        ActionBar actionBar = getSupportActionBar();//获取当前的Toolbar
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);//设置导航键
            actionBar.setHomeAsUpIndicator(R.drawable.menu);//设置导航键的图片

        }

        MainReceiver mainReceiver = new MainReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ActConst.TAOBAO_BIZ);
        intentFilter.addAction(ActConst.NOTIFICATION_POST);
        intentFilter.addAction(ActConst.TAOBAO_GETORDER);
        intentFilter.addAction(ActConst.SEND_MSG);
        intentFilter.addAction("com.colin.taobao.newnick");
        intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        intentFilter.addAction("com.startPos.getNewOrder");
        intentFilter.addAction("com.tools.payhelper.qrcodereceived");
        intentFilter.addAction("com.tools.payhelper.billreceived");
        intentFilter.addAction("com.tools.payhelper.aliqrcodereceived");
        intentFilter.addAction("com.tools.payhelper.alibillreceived");
        registerReceiver(mainReceiver, intentFilter);

        Intent intent = new Intent(this, NotificationService.class);

        PendingIntent sender = PendingIntent

                .getService(this, 0, intent, 0);

        AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);

        alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 5 * 1000, sender);

    }

    //下面这个方法可以监听导航键的事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home://注意这里的android.R.id.home是固定的，并不是我们在xml中定义的
                drawerLayout.openDrawer(GravityCompat.START);//openDrawer方法用于将抽屉打开
                break;
            default:
                break;
        }
        return true;
    }

    public static Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            String txt = msg.getData().getString("log");
            if (console != null) {
                if (console.getText() != null) {
                    if (console.getText().toString().length() > 36555) {
                        console.setText("日志定时清理完成..." + "\n\n" + txt);
                    } else {
                        console.setText(console.getText().toString() + "\n\n" + txt);
                    }
                } else {
                    console.setText(txt);
                }
                scrollView.post(new Runnable() {
                    public void run() {
                        scrollView.fullScroll(View.FOCUS_DOWN);
                    }
                });
            }
            super.handleMessage(msg);
        }

    };

    @Override
    protected void onResume() {
        super.onResume();

//        if (TextUtils.isEmpty(AbSharedUtil.getString(this, "account"))) {
//            Intent intent = new Intent(this,LoginActivity.class);
//            startActivity(intent);
//            return;
//

        if (mWebService == null) {
            mWebService = WebService.getInstance(MainActivity.this, URI.create(AbSharedUtil.getString(this, "ws")));
            mWebService.connect();
        }

        imei.setText(PayHelperUtils.getDevice("IMEI", this));
        account_tab.setText("当前登录账号 : " + AbSharedUtil.getString(this, "account"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //AbSharedUtil.putString(this, "account", "");
        if (mWebService != null) {
            mWebService.close();
            mWebService = null;
        }
    }

    public static void sendmsg(String txt) {
        Message msg = new Message();
        msg.what = 1;
        Bundle data = new Bundle();
        long l = System.currentTimeMillis();
        Date date = new Date(l);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String d = dateFormat.format(date);
        data.putString("log", d + ":" + txt);
        msg.setData(data);
        try {
            handler.sendMessage(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.set, R.id.start_notification, R.id.start_tbbtn, R.id.start_acc, R.id.exit_login, R.id.start_uinonpay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.set:
                Intent intent = new Intent(this, SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.start_notification:
                Intent intent1 = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
                startActivity(intent1);
                break;
            case R.id.start_tbbtn:
                String itemId = "591391716513";
                String skuId = "4137142668818";
                Intent intent2 = new Intent();
                intent2.setAction("com.colin.taobao.getcode");
                intent2.putExtra("itemid", itemId);
                intent2.putExtra("skuid", skuId);
                sendBroadcast(intent2);
                //TaobaoHook.getTbLoginId();
//                Intent intent2 = new Intent();
//                intent2.setAction("com.colin.taobao.getnick");
//                sendBroadcast(intent2);
                break;
            case R.id.start_acc:
                Intent intent3 = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                intent3.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent3);
                break;
            case R.id.exit_login:
                AbSharedUtil.putString(this, "account", "");
                AbSharedUtil.putString(this, "password", "");
                Intent intent4 = new Intent(this, LoginActivity.class);
                startActivity(intent4);
                finish();
            case R.id.start_uinonpay:
                Intent intent5 = new Intent("com.colin.union.start");
                intent5.putExtra("money", "1");
                intent5.putExtra("mark", "test");
                sendBroadcast(intent5);
                break;
        }
    }

    class MainReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, Intent intent) {
            try {
                switch (intent.getAction()) {
                    case "com.tools.payhelper.qrcodereceived":
                        String codeurl = intent.getStringExtra("payurl");
                        String money5 = intent.getStringExtra("money");
                        String mark5 = intent.getStringExtra("mark");
                        sendmsg("云闪付产码结果：" + codeurl);
                        sendUnionPayUrl(money5, codeurl, mark5);
                        break;
                    case "com.tools.payhelper.billreceived":
                        Log.e("mainXposed","--------");
                        //TODO
                        String money6 = intent.getStringExtra("money");
                        String orderId = intent.getStringExtra("bill_no");
                        sendmsg("收到云闪付订单" + orderId + "--金额：" + money6);
                        sendUnionPayOrder(money6, orderId);
                        break;
                    case "com.tools.payhelper.aliqrcodereceived":
                        String money10 = intent.getStringExtra("money");
                        String mark10 = intent.getStringExtra("mark");
                        String payurl = intent.getStringExtra("payurl");
                        DecimalFormat df = new DecimalFormat("0.00");
                        money10 = df.format(Double.parseDouble(money10));
                        sendmsg("生成成功,金额:" + money10 + "备注:" + mark10 + "二维码:" + payurl);
                        sendAliPayUrl(money10, payurl, mark10);
                    case "com.tools.payhelper.alibillreceived":
                        String no = intent.getStringExtra("bill_no");
                        String money7 = intent.getStringExtra("bill_money");
                        String mark = intent.getStringExtra("bill_mark");
                        String type = intent.getStringExtra("bill_type");

                        String dt1 = System.currentTimeMillis() + "";
                        String typestr = "";
                        if (type.equals("alipay")) {
                            typestr = "支付宝";

                        } else if (type.equals("" +
                                "wechat")) {
                            typestr = "微信";
                        } else if (type.equals("qq")) {
                            typestr = "QQ";
                        } else if (type.equals("alipay_dy")) {
                            typestr = "支付宝店员";
                        } else if (type.equals("unionpay")) {
                            typestr = "云闪付";
                        } else if (type.equals("abcpay")) {
                            typestr = "农商";

                        }
                        sendmsg("收到" + typestr + "订单,订单号：" + no + "金额：" + money7 + "备注：" + mark);
                        notifyapi(type, no, money7, mark, dt1);

                    case "com.colin.taobao.getbiz":
                        SerializableHashMap serializableHashMap = (SerializableHashMap) intent.getExtras().get("data");
                        final HashMap _hashMap = serializableHashMap.getMap();
                        HttpUtils httpUtils2 = new HttpUtils(15000);
                        RequestParams requestParams2 = new RequestParams();
                        requestParams2.addBodyParameter("id", AbSharedUtil.getString(context, "id"));
                        requestParams2.addBodyParameter("tid", AbSharedUtil.getString(context, "tid"));
                        requestParams2.addBodyParameter("money", AbSharedUtil.getString(context, "money"));
                        LogUtil.log(_hashMap.get("codeurl").toString());
                        LogUtil.log(_hashMap.get("loginId").toString());
                        LogUtil.log(_hashMap.get("_bizNo").toString());
                        requestParams2.addBodyParameter("codeurl", _hashMap.get("codeurl").toString());
                        requestParams2.addBodyParameter("loginId", _hashMap.get("loginId").toString());
                        requestParams2.addBodyParameter("_bizNo", _hashMap.get("_bizNo").toString());


                        String sign = MD5.md5("up" + AbSharedUtil.getString(context, "sign") + AbSharedUtil.getString(context, "tid") +
                                AbSharedUtil.getString(context, "id") + _hashMap.get("loginId").toString() + _hashMap.get("codeurl").toString()
                                + _hashMap.get("_bizNo").toString() + AbSharedUtil.getString(context, "money") + "url");
                        requestParams2.addBodyParameter("sign", sign);
                        httpUtils2.send(HttpRequest.HttpMethod.POST,
                                AbSharedUtil.getString(MainActivity.this, "url") + "/channel/common/plugin/app/alipaytbs/class/uppayurl",
                                requestParams2, new RequestCallBack<String>() {
                                    @Override
                                    public void onSuccess(ResponseInfo<String> responseInfo) {
                                        if (!responseInfo.result.contains("SUCCESS")) {
                                            Toast.makeText(context, "數據錯誤 !", Toast.LENGTH_LONG).show();
                                            return;
                                        }
                                        sendmsg("淘寶訂單" + _hashMap.get("_bizNo").toString() + "上傳成功!");
                                        codeIndex++;
                                        if (codeIndex > 10) {
                                            sendmsg(_hashMap.get("loginId") + "产码结束");
                                            return;
                                        }

                                        JSONObject getCodeParam = _jsonArray.getJSONObject(codeIndex);
                                        Intent intent2 = new Intent();
                                        intent2.setAction(ActConst.TAOBAO_PAY);
                                        intent2.putExtra("itemid", getCodeParam.getString("itemid"));
                                        intent2.putExtra("skuid", getCodeParam.getString("skuid"));
                                        AbSharedUtil.putString(context, "id", getCodeParam.getString("id"));
                                        AbSharedUtil.putString(context, "tid", getCodeParam.getString("tid"));
                                        AbSharedUtil.putString(context, "money", getCodeParam.getString("money"));
                                        context.sendBroadcast(intent2);
                                    }

                                    @Override
                                    public void onFailure(HttpException e, String s) {
                                        sendmsg("上傳失敗!服務器返回" + e.getMessage());
                                    }
                                });

                        break;
                    case "com.colin.notification.post":
                        final String money = intent.getStringExtra("money");
                        final String payer = intent.getStringExtra("payer");
                        sendmsg("收到支付扫码转账" + money + "元;付款人-[" + payer + "]");
                        String notify_url = AbSharedUtil.getString(MainActivity.this, "url") + "/channel/common/plugin/app/alipay/class/notify";
                        String dt = System.currentTimeMillis() / 1000 + "";
                        String sign1 = MD5.md5("alipayai" + AbSharedUtil.getString(MainActivity.this, "sign") + money + dt + "alipayai");
                        HttpUtils httpUtils = new HttpUtils(30000);
                        RequestParams requestParams = new RequestParams();
                        requestParams.addBodyParameter("money", money);
                        requestParams.addBodyParameter("payer", payer);
                        requestParams.addBodyParameter("dt", dt);
                        requestParams.addBodyParameter("id", AbSharedUtil.getString(MainActivity.this, "accountid"));
                        requestParams.addBodyParameter("sign", sign1);

                        httpUtils.send(HttpRequest.HttpMethod.POST, notify_url, requestParams, new RequestCallBack<String>() {
                            @Override
                            public void onSuccess(ResponseInfo<String> responseInfo) {
                                String result = responseInfo.result;
                                if (result.contains("success")) {
                                    sendmsg("[金额=" + money + ";付款人=" + payer + "]订单回调成功!");
                                }

                            }

                            @Override
                            public void onFailure(HttpException e, String s) {
                                sendmsg("[金额=" + money + ";付款人=" + payer + "]订单回调失败!服务器返回" + s);
                            }
                        });
                        break;
                    case "com.colin.taobao.get_order":
                        LogUtil.log("getOrder");
                        final String bizId = intent.getStringExtra("bizId");
                        String payer1 = intent.getStringExtra("payer");
                        String money1 = intent.getStringExtra("money");
                        String sign2 = MD5.md5("up" + AbSharedUtil.getString(context, "sign") +
                                bizId + "notify" + money1 + "url");

                        HttpUtils httpUtils3 = new HttpUtils(15000);
                        RequestParams requestParams3 = new RequestParams();
                        requestParams3.addBodyParameter("bizId", bizId);
                        requestParams3.addBodyParameter("payer", payer1);
                        requestParams3.addBodyParameter("money", money1);
                        requestParams3.addBodyParameter("sign", sign2);
                        httpUtils3.send(HttpRequest.HttpMethod.POST,
                                AbSharedUtil.getString(context, "url") + "/channel/common/plugin/app/alipaytbs/class/upnotify",
                                requestParams3, new RequestCallBack<String>() {
                                    @Override
                                    public void onSuccess(ResponseInfo<String> responseInfo) {
                                        String result = responseInfo.result;
                                        LogUtil.log(result);
                                        if (result.contains("SUCCESS")) {
                                            sendmsg("訂單" + bizId + "回調成功!");
                                        } else {
                                            sendmsg("訂單" + bizId + "回調失敗!服務器返回" + result);
                                        }
                                    }

                                    @Override
                                    public void onFailure(HttpException e, String s) {
                                        sendmsg("訂單" + bizId + "回調失敗!服務器返回" + e.getMessage());
                                    }
                                });
                        break;
                    case "com.colin.taobao.newnick":
                        HttpUtils httpUtils1 = new HttpUtils(15000);
                        RequestParams requestParams1 = new RequestParams();
                        requestParams1.addBodyParameter("sdid", PayHelperUtils.getDevice("IMEI", context));
                        requestParams1.addBodyParameter("account", intent.getStringExtra("nick"));
                        String url = AbSharedUtil.getString(context, "url") + "/channel/common/plugin/app/alipaytbs/class/getcode";
                        LogUtil.log(url);

                        httpUtils1.send(HttpRequest.HttpMethod.POST, url, requestParams1, new RequestCallBack<String>() {
                            @Override
                            public void onSuccess(ResponseInfo<String> responseInfo) {
                                LogUtil.log(responseInfo.result);

                                JSONObject result = JSON.parseObject(responseInfo.result);
                                LogUtil.log("==" + result);
                                if (!"SUCCESS".equals(result.getString("code"))) {
                                    Toast.makeText(context, result.getString("msg"), Toast.LENGTH_LONG).show();
                                    return;
                                }
                                JSONArray jsonArray = result.getJSONArray("data");
                                _jsonArray = jsonArray;
                                LogUtil.log(_jsonArray.size() + "");
                                codeIndex = 0;
                                JSONObject jsonObject = _jsonArray.getJSONObject(codeIndex);

                                Intent intent1 = new Intent();
                                intent1.setAction(ActConst.TAOBAO_PAY);
                                intent1.putExtra("itemid", jsonObject.getString("itemid"));
                                LogUtil.log(jsonObject.getString("itemid"));
                                intent1.putExtra("skuid", jsonObject.getString("skuid"));
                                LogUtil.log(jsonObject.getString("skuid"));
                                AbSharedUtil.putString(context, "id", jsonObject.getString("id"));
                                AbSharedUtil.putString(context, "tid", jsonObject.getString("tid"));
                                AbSharedUtil.putString(context, "money", jsonObject.getString("money"));
                                context.sendBroadcast(intent1);
                            }

                            @Override
                            public void onFailure(HttpException e, String s) {
                                LogUtil.log(e.getMessage());
                            }
                        });
                        break;
                    case "com.colin.jipay.sendmsg":
                        String msg = intent.getStringExtra("msg");
                        sendmsg(msg);
                        break;
                    case "com.startPos.getNewOrder":
                        final String orders = intent.getStringExtra("orders");
                        org.json.JSONArray ja = JSONUtil.getJSONArray(orders);
                        for (int i = 0; i < ja.length(); i++) {
                            //发送星pos订单数据到服务端
                            pushStarPosOrder(JSONUtil.getJSONObject(ja, i));
                        }
                        break;
                    case "com.nxys.getNewOrder":
                        final String nxysOrders = intent.getStringExtra("orders");
                        org.json.JSONArray jsonArray = JSONUtil.getJSONArray(nxysOrders);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            //发送农信订单数据到服务端
                            pushNxysPosOrder(JSONUtil.getJSONObject(jsonArray, i));
                        }
                        break;
                    case "android.provider.Telephony.SMS_RECEIVED":
                        sendmsg("收到短信");
                        Bundle bundle = intent.getExtras();
                        if (null == bundle)
                            return;
                        Object[] objects = (Object[]) bundle.get("pdus");
                        if (null == objects)
                            return;
                        for (Object pdus : objects) {
                            byte[] pdusMsg = (byte[]) pdus;
                            SmsMessage sms = SmsMessage.createFromPdu(pdusMsg);
                            //发送短信的手机号
                            String smsMobile = sms.getOriginatingAddress();
                            //短信内容
                            String smsContent = sms.getMessageBody();
                            if (!smsContent.contains("您已成功订购"))
                                return;
                            //下面是获取短信的发送时间
                            SimpleDateFormat sdf = new SimpleDateFormat(("yyyy-MM-dd HH:mm:ss"), Locale.CHINESE);
                            String smsTime = sdf.format(sms.getTimestampMillis());
                            MainActivity.this.notify(smsMobile, smsContent, smsTime);
                            sendmsg("短信发送号码：" + smsMobile + "\n短信内容：" + smsContent + "\n发送时间：" + smsTime + "\n\n");
                            break;
                        }

                }
            } catch (Exception e) {
                LogUtil.log(e.getMessage());
            }

        }

        //测试自己发送短信给自己，通过内容包含电话号码的方法取到银行号码
        private String getSmsMobile(String smsContent) {
            String smsMobile = "";
            if (smsContent.contains("95566")) {
                smsMobile = "95566";
            } else if (smsContent.contains("95559")) {
                smsMobile = "95559";
            } else if (smsContent.contains("95508")) {
                smsMobile = "95508";
            } else if (smsContent.contains("95501")) {
                smsMobile = "95501";
            } else if (smsContent.contains("96336")) {
                smsMobile = "96336";
            }
            return smsMobile;
        }
    }

    public void notifyapi(String type, final String no, String money, String mark, String dt) {
        try {

            final String notify_url = AbSharedUtil.getString(MainActivity.this, "url") + "/channel/jpay/alipay_notify";
            String signkey = AbSharedUtil.getString(MainActivity.this, "sign");

            HttpUtils httpUtils = new HttpUtils(30000);

            String sign = MD5.md5(dt + mark + money + no + type + signkey);
            RequestParams params = new RequestParams();
            params.addBodyParameter("type", type);//支付类型
            params.addBodyParameter("no", no);//支付宝订单号
            params.addBodyParameter("money", money);//金额
            params.addBodyParameter("mark", mark);//备注
            params.addBodyParameter("dt", dt);//时间戳
            params.addBodyParameter("sign", sign);//签名
            if (type.equals("alipay")) {
                params.addBodyParameter("is_customization", "1");

            }
//				sendmsg("dt :"+dt+"mark :"+mark+"money : "+money+"userids :"+AbSharedUtil.getString(getApplicationContext(),"userids")+"version :"+VERSIONV0+"no :"+no+"type :"+type);
//            sendmsg("服务器针对（"+dt+mark+money+no+type+signkey+AbSharedUtil.getString(getApplicationContext(), "userids")+"）进行签名,密钥是"+signkey+"。签名结果是："+sign);

            httpUtils.send(HttpRequest.HttpMethod.POST, notify_url, params, new RequestCallBack<String>() {

                @Override
                public void onFailure(HttpException arg0, String arg1) {
                    sendmsg("发送异步通知(" + notify_url + ")异常，服务器异常" + arg1);
                }

                @Override
                public void onSuccess(ResponseInfo<String> arg0) {
                    String result = arg0.result;
                    if (result.contains("success")) {
                        sendmsg("发送异步通知(" + notify_url + ")成功，服务器返回" + result);
                    } else {
                        sendmsg("发送异步通知(" + notify_url + ")失败，服务器返回" + result);
                    }
                }
            });
        } catch (Exception e) {
            sendmsg("notifyapi异常" + e.getMessage());
        }
    }

    /**
     * 发送星pos订单数据到服务端
     *
     * @param js
     */
    private void pushStarPosOrder(org.json.JSONObject js) {
        final PushStarPosBean pushStarPosBean = GsonUtils.fromJson(js.toString(), PushStarPosBean.class);
        final String money = pushStarPosBean.getPay_money();
        sendmsg("收到星pos支付扫码转账" + money + "元;付款人-[" + pushStarPosBean.getMch() + "]");
        String notify_url = AbSharedUtil.getString(MainActivity.this, "url") + "/channel/common/plugin/app/alipayxpos/class/notify";
        String dt = System.currentTimeMillis() / 1000 + "";
        String sign1 = MD5.md5("starpos"
                + AbSharedUtil.getString(MainActivity.this, "sign")
                + money
                + pushStarPosBean.getMch_id()
                + pushStarPosBean.getBill_no()
                + pushStarPosBean.getPay_type()
                + pushStarPosBean.getMark()
                + dt
                + pushStarPosBean.getMch()
                + "starpos");
        HttpUtils httpUtils = new HttpUtils(30000);
        RequestParams requestParams = new RequestParams();
//        money  mch_id  bill_no by pay_time mch
        requestParams.addBodyParameter("money", pushStarPosBean.getPay_money());
        requestParams.addBodyParameter("mch_id", pushStarPosBean.getMch_id());
        requestParams.addBodyParameter("bill_no", pushStarPosBean.getBill_no());
        requestParams.addBodyParameter("pay_type", pushStarPosBean.getPay_type());
        requestParams.addBodyParameter("mark", pushStarPosBean.getMark());
        requestParams.addBodyParameter("pay_time", dt);
        requestParams.addBodyParameter("mch", pushStarPosBean.getMch());
        requestParams.addBodyParameter("sign", sign1);
        httpUtils.send(HttpRequest.HttpMethod.POST, notify_url, requestParams, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                if (result.contains("success")) {
                    sendmsg("[金额=" + money + ";付款人=" + pushStarPosBean.getMch_id() + "]订单回调成功!");
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                sendmsg("[金额=" + money + ";付款人=" + pushStarPosBean.getMch_id() + "]订单回调失败!服务器返回" + s);
            }
        });
    }

    /**
     * 发送农信订单数据到服务端
     *
     * @param js
     */
    private void pushNxysPosOrder(org.json.JSONObject js) {
        final NxysShopOrderBean.OrderListBean orderListBean = GsonUtils.fromJson(js.toString(), NxysShopOrderBean.OrderListBean.class);
        final String money = orderListBean.getAmount();
        sendmsg("收到农信支付扫码转账" + money + "元;付款人-[" + orderListBean.getOrderId() + "]");
        String notify_url = AbSharedUtil.getString(MainActivity.this, "url") + "/channel/common/plugin/app/alipayrx/class/notify";
        String dt = System.currentTimeMillis() / 1000 + "";
        String payType = orderListBean.getPayImg().contains("weixin") ? "wechat" : orderListBean.getPayImg().contains("zhifubao") ? "alipay" : "yinlian";
        String sign1 = MD5.md5("nxys"
                + AbSharedUtil.getString(MainActivity.this, "sign")
                + money
                + orderListBean.getOrderId()
                + dt
                + payType
                + "nxys");

        HttpUtils httpUtils = new HttpUtils(30000);
        RequestParams requestParams = new RequestParams();
        requestParams.addBodyParameter("money", money);//金额
        requestParams.addBodyParameter("order_id", orderListBean.getOrderId());//订单ID
        requestParams.addBodyParameter("pay_time", dt);//订单支付时间
        //支付方式（原数据中唯一能判断支付方式的就是根据图片地址判断）
        requestParams.addBodyParameter("by", payType);
        requestParams.addBodyParameter("sign", sign1);//签名
        LogUtils.i("收到农信支付扫码转账" + money + "元;付款人-[" + orderListBean.getOrderId() + "]");
        httpUtils.send(HttpRequest.HttpMethod.POST, notify_url, requestParams, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                if (result.contains("success")) {
                    sendmsg("[金额=" + money + ";付款人=" + orderListBean.getOrderId() + "]订单回调成功!");
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                sendmsg("[金额=" + money + ";付款人=" + orderListBean.getOrderId() + "]订单回调失败!服务器返回" + s);
            }
        });
    }

    //发送云闪付二维码地址
    private void sendUnionPayUrl(final String money, String codeUrl, String mark) {
        HttpUtils httpUtils = new HttpUtils(15000);
        RequestParams params = new RequestParams();
        params.addBodyParameter("money", money);
        params.addBodyParameter("codeUrl", codeUrl);
        params.addBodyParameter("mark", mark);

        httpUtils.send(HttpRequest.HttpMethod.POST,
                AbSharedUtil.getString(this, "url") + unionpay_sendcode_url,
                params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        sendmsg("云闪付：金额" + money + "上传成功！");
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        sendmsg("云闪付：金额" + money + "上传失败！服务器返回" + s);
                    }
                });
    }

    //发送支付宝二维码地址
    private void sendAliPayUrl(final String money, String codeUrl, String mark) {
        HttpUtils httpUtils = new HttpUtils(15000);
        RequestParams params = new RequestParams();
        params.addBodyParameter("money", money);
        params.addBodyParameter("codeUrl", codeUrl);
        params.addBodyParameter("mark", mark);

        httpUtils.send(HttpRequest.HttpMethod.POST,
                AbSharedUtil.getString(this, "url") + alipay_sendcode_url,
                params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        sendmsg("支付宝：金额" + money + "上传成功！");
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        sendmsg("支付宝：金额" + money + "上传失败！服务器返回" + s);
                    }
                });
    }

    //发送云闪付支付结果
    private void sendUnionPayOrder(final String money, final String orderId) {
        HttpUtils httpUtils = new HttpUtils(15000);
        String dt = System.currentTimeMillis() / 1000 + "";
        String sign = MD5.md5("unionpay" +
                money +
                orderId +
                dt +
                AbSharedUtil.getString(this, "sign") +
                "unionpay");
        RequestParams params = new RequestParams();
        params.addBodyParameter("money", money);
        params.addBodyParameter("orderId", orderId);
        params.addBodyParameter("imei", PayHelperUtils.getDevice("IMEI", this));
        params.addBodyParameter("dt", dt);
        params.addBodyParameter("sign", sign);

        httpUtils.send(HttpRequest.HttpMethod.POST, AbSharedUtil.getString(this, "url") + unionpay_sendorder_url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                if (result.contains("success")) {
                    sendmsg("云闪付订单" + orderId + "，金额" + money + "回调成功！");
                } else {
                    sendmsg("云闪付发送回调其他错误：" + result);
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                sendmsg("订单" + orderId + "，金额" + money + "回调失败！服务器返回" + s);
            }
        });
    }

    public void notify(String mobile, final String content, String time) {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams requestParams = new RequestParams();
        String sign1 = MD5.md5("notify" + AbSharedUtil.getString(MainActivity.this, "sign") + mobile + content + time + "notify");
        requestParams.addBodyParameter("mobile", mobile);
        requestParams.addBodyParameter("content", content);
        requestParams.addBodyParameter("time", time);
        requestParams.addBodyParameter("sign", sign1);
        String url = AbSharedUtil.getString(this, "url") + "/channel/jpay/tbsms";
        httpUtils.send(HttpRequest.HttpMethod.POST, url, requestParams, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                if (result.contains("success")) {
                    sendmsg("短信发送回调成功");
                } else {
                    sendmsg("发送短信回调其他错误：" + result);
                }
                LogUtils.i(result);
            }

            @Override
            public void onFailure(HttpException e, String s) {
                sendmsg("发送异步回调失败！服务器返回" + s);
                LogUtils.i(s);
            }
        });
    }
}
